/*
 * @lxc: 
 * @Version: 2.0
 * @Autor: lxc
 * @Date: 2020-12-14 13:52:04
 * @LastEditors: lxc
 * @LastEditTime: 2020-12-18 13:46:46
 */

const express = require("express");
const router = express.Router();
const bcrypt = require('bcrypt');
const jwt = require("jsonwebtoken");
const gravatar = require("gravatar");
const keys = require("../../config/keys").secretOrKey;
const passport = require("passport");
const User = require("../../models/User");
// 引入验证方法
const validateRegisterInput = require("../../validation/register");
const validateLoginInput = require("../../validation/login");

// $route GET api/users/test
// @desc 返回请求的JSON数据
// @access public
router.get("/test", (req, res) => {
    res.json({ msg: 'longin works' });
})

// $oute POST api/users/register
// @desc 返回的请求的json
// @access public
router.post('/register', (req, res) => {
    const { errors, isValid } = validateRegisterInput(req.body);
    // 判断isValid是否通过
    if (!isValid) {
        return res.status(400).json(errors)
    }
    // 查询数据库是否拥有邮箱
    let body = req.body;

    User.findOne({ email: body.email }).then(user => {
        if (user) {
            return res.status(400).json({ msg: '邮箱已被注册' });
        } else {
            const avatar = gravatar.url(body.email, { s: '200', r: 'pg', d: 'mm' });
            const newUser = new User({
                name: body.name,
                email: body.email,
                avatar,
                password: body.password
            })
            // 密码加密
            bcrypt.genSalt(10, (err, salt) => {
                bcrypt.hash(newUser.password, salt, (err, hash) => {
                    if (err) throw err;
                    newUser.password = hash;
                    newUser.save().then(user => {
                        res.json(user);
                    }, err => {
                        console.log(err);
                    })
                })
            })
        }
    }).catch(err => {
        console.log(err);
    })

})

// $oute POST api/users/login
// @desc 返回token jwt passport
// @access public
router.post("/login", (req, res) => {
    const { errors, isValid } = validateLoginInput(req.body);
    // 判断isValid是否通过
    if (!isValid) {
        return res.status(400).json(errors)
    }
    const email = req.body.email;
    const password = req.body.password;
    // 查询数据库
    User.findOne({ email }).then(user => {
        if (!user) {
            return res.status(400).json({ msg: '用户不存在' })
        }
        // // 密码匹配
        bcrypt.compare(password, user.password).then(isMatch => {
            if (isMatch) {
                // jwt.sign("规则","加密名字","过期时间","箭头函数")
                const rule = { id: user.id, name: user.name };
                jwt.sign(rule, keys, { expiresIn: 3600 }, (err, token) => {
                    if (err) throw err;
                    res.json({ success: true, token: "Bearer " + token })
                })
            } else {
                return res.status(400).json({ msg: "密码错误" });
            }
        })
        // bcrypt.compare(password, user.password, (err, isMatch) => {
        // if (isMatch) {
        //         res.json({ msg: 'success' })
        //     } else {
        //         return res.status(400).json({ password: "密码错误" });
        //     }
        // })
    })
})
// $oute GET api/users/current
// @desc 返回curent user
// @access Private
router.get("/current", passport.authenticate('jwt', { session: false }), (req, res) => {
    res.json({
        id: req.user.id,
        name: req.user.name,
        email: req.user.email
    })
})
module.exports = router;